package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.CMUtil
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import cn.com.kh.dh.HttpClient
import cn.com.kh.getProperty
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @projectName: ngsapitask-hst
 * @package: cn.com.kh
 * @className: apiCustomerMerge
 * @author: LiJT
 * @description: 客户信息合并接口
 * @date: 2022-12-19 14:03
 * @version: 1.0
 */

public class apiCustomerMerge implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiCustomerMerge.class);
    private static String log_Prefix = "客户信息合并接口-";
    private static String log_All = "";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn(log_Prefix + "API被非法IP调用-Request Not Allow!");
            return "Request Not Allow!";
        }

        // 获取操作No
        String Oper_No = KHUtil.getRandomString(36);
        int Oper_Num = 0;

        // 获取数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        String Syncpram = "";

        String getMethod = request.getMethod();
        if (getMethod == "GET") {
            Syncpram = request.getQueryString();
            log.info("接收调用GET参数信息：" + Syncpram);
        } else if (getMethod == "POST") {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }

            log.info(log_Prefix + "接收调用POST报文信息：" + System.getProperty("line.separator") + Syncpram);
        }

        JSONObject resultBody = new JSONObject();
        resultBody.put("code", "1");
        resultBody.put("msg", "调用成功");

        try {
            // 反序列化请求报文
            JSONObject callJson = JSONObject.fromObject(Syncpram);

            // 解析请求信息
            String op_type = callJson.getString("op_type");
            String op_comments = callJson.getString("op_comments");
            String op_staff_id = callJson.getString("op_staff_id");
            String op_rolegroup_id = callJson.getString("op_rolegroup_id");
            String old_customer_guid = callJson.getString("old_customer_guid"); // 原Customer_Guid
            String new_customer_guid = callJson.getString("new_customer_guid"); // 新Customer_Guid
            log.debug(log_Prefix + "代理API基础信息:op_type：" + op_type + " old_customer_guid：" + old_customer_guid + " new_customer_guid：" + new_customer_guid + " op_comments：" + op_comments);

            String nullCheckInfo = KHUtil.isNullMSG("op_type", op_type) + KHUtil.isNullMSG("op_comments", op_comments) + KHUtil.isNullMSG("op_rolegroup_id", op_rolegroup_id) + KHUtil.isNullMSG("op_staff_id", op_staff_id) + KHUtil.isNullMSG("old_customer_guid", old_customer_guid) + KHUtil.isNullMSG("new_customer_guid", new_customer_guid);
            log.debug(log_Prefix + "非空校验:" + nullCheckInfo);

            if (!KHUtil.isNull(nullCheckInfo)) {

                resultBody.put("code", "-2");
                resultBody.put("msg", "非空校验不满足!" + nullCheckInfo);
                log.warn(log_Prefix + "处理完成返回结果:" + resultBody.toString());
                return resultBody.toString();

            } else {
                if (old_customer_guid == new_customer_guid) {
                    resultBody.put("code", "-3");
                    resultBody.put("msg", "原客户和新客户Guid一致不允许合并!");
                    log.warn(log_Prefix + "处理完成返回结果:" + resultBody.toString());
                    return resultBody.toString();

                }
            }

            // 操作网聊专属路由表
            String selectOldSQL = '''Select R1.Customer_Guid, R1.Customerid, R1.Customername, R1.Open_Id, R3.Route_Guid, R3.Ownerstaff_Id, R1.Webchat_Target_Id
                                          From Customer R1
                                          Left Join Chat_Multichannel_Route R3
                                            On R1.Customer_Guid = R3.Customer_Guid
                                         Where R1.Customer_Guid = ?''';
            List<Map<String, Object>> selectOldResult = jt.queryForList(selectOldSQL, old_customer_guid);
            log.debug(log_Prefix + "老客户检查结果:" + selectOldResult.toString());

            if (selectOldResult.size() > 0) {
                String Old_Route_Guid = selectOldResult.get(0).get("Route_Guid").toString();
                String Old_Open_Id = selectOldResult.get(0).get("Open_Id").toString();
                String Old_Webchat_Target_Id = selectOldResult.get(0).get("Webchat_Target_Id").toString();

                // 获取目标Customer信息&检查数据是否已经存在
                String selectExistSQL = '''Select R1.Customer_Guid, R1.Customerid, R1.Customername, R1.Open_Id, R3.Route_Guid, R3.Ownerstaff_Id
                                          From Customer R1
                                          Left Join Chat_Multichannel_Route R3
                                            On R1.Customer_Guid = R3.Customer_Guid
                                         Where R1.Customer_Guid = ?''';
                List<Map<String, Object>> selectExistResult = jt.queryForList(selectExistSQL, new_customer_guid);
                log.debug(log_Prefix + "新客户检查结果:" + selectExistResult.toString());

                // 数据库操作
                if (selectExistResult.size() > 0) {
                    String Route_Guid = selectExistResult.get(0).get("Route_Guid").toString();
                    String Open_Id = selectExistResult.get(0).get("Open_Id").toString();

                    if (KHUtil.isNull(Route_Guid)) {
                        String insertSQL = '''Insert Into Chat_Multichannel_Route
                                          (Route_Guid,
                                           Customer_Guid,
                                           Openid,
                                           Ownerstaff_Id,
                                           Curvisitchannel,
                                           Firstvisittime,
                                           Curvisittime,
                                           Bind_Status,
                                           Lastupdateinfotime)
                                        Values
                                          (Uuid(), Customer_Guid, Openid, Ownerstaff_Id, Curvisitchannel, Now(), Now(), Bind_Status, Now())''';
                        Oper_Num = jt.update(insertSQL, new_customer_guid, Old_Open_Id, op_staff_id, "WhatsApp", 1);
                        log.debug(log_Prefix + "新增数据(" + new_customer_guid + ") Chat_Multichannel_Route数量：" + Oper_Num);
                    } else {
                        String updateSQL = "Update Chat_Multichannel_Route Set Openid = ?, Lastupdateinfotime = Now() Where Route_Guid = ?";
                        Oper_Num = jt.update(updateSQL, Old_Open_Id, Route_Guid);
                        log.debug(log_Prefix + "更新数据(" + new_customer_guid + ") Chat_Multichannel_Route数量：" + Oper_Num);
                    }

                    // 删除原Customer表数据
                    String bakDataSQL = '''Select R1.*, R3.*
                                          From Customer R1
                                          Left Join Chat_Multichannel_Route R3
                                            On R1.Customer_Guid = R3.Customer_Guid
                                         Where R1.Customer_Guid = ?''';
                    List<Map<String, Object>> bakDataResult = jt.queryForList(bakDataSQL, old_customer_guid);
                    log.debug(log_Prefix + "老客户检查结果:" + bakDataResult.toString());

                    LogToDB.toSys_Oper_Log(eliteBean, Oper_No, "Title", op_type, op_comments, "-1", "Customer", bakDataResult.toString(), "", op_rolegroup_id, op_staff_id, "0");
                    Oper_Num = jt.update("Delete From Customer Where Customer_Guid = ?", old_customer_guid);
                    log.debug(log_Prefix + "删除原客户Customer 数量：" + Oper_Num);

                    Oper_Num = jt.update("Delete From Chat_Multichannel_Route Where Customer_Guid = ?", old_customer_guid);
                    log.debug(log_Prefix + "删除原客户Chat_Multichannel_Route 数量：" + Oper_Num);

                    Oper_Num = jt.update("Update Customer Set Partner_Guid = ?, Open_Id = ?, Webchat_Target_Id = ? Where Customer_Guid = ?", old_customer_guid, Old_Open_Id, Old_Webchat_Target_Id, new_customer_guid);
                    log.debug(log_Prefix + "更新新客户关联客户Partner_Guid 数量：" + Oper_Num);

                    Oper_Num = jt.update("Update Event Set Customer_Guid = ? Where Customer_Guid = ?", new_customer_guid, old_customer_guid);
                    log.debug(log_Prefix + "更新原客户关联Event 数量：" + Oper_Num);

                    Oper_Num = jt.update("Update Record Set Customer_Guid = ? Where Customer_Guid = ?", new_customer_guid, old_customer_guid);
                    log.debug(log_Prefix + "更新原客户关联 Record 数量：" + Oper_Num);

                } else {
                    log_All = log_Prefix + "当前要合并的目标客户未检索到信息(" + new_customer_guid + ") 数量：" + selectExistResult.size();
                    resultBody.put("code", "-1");
                    resultBody.put("msg", log_All);
                    log.warn(log_Prefix + "处理完成返回结果:" + resultBody.toString());
                    return resultBody.toString();
                }
            } else {
                log_All = log_Prefix + "当前要合并的原客户未检索到信息(" + old_customer_guid + ") 数量：" + selectOldResult.size();
                resultBody.put("code", "-1");
                resultBody.put("msg", log_All);
                log.warn(log_Prefix + "处理完成返回结果:" + resultBody.toString());
                return resultBody.toString();
            }

        } catch (Exception e) {
            log.error(log_Prefix + "接口处理异常", e);
            // 失败返回
            resultBody.put("code", "-1");
            resultBody.put("msg", "调用合并异常：" + e.getMessage());

        }

        return resultBody.toString();
    }

}
